// userPageB/pages/userStore/cardPay/cardPay.js
const app = getApp()
const WXAPI = require("../../../../api/api")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    nvabarData: {
      showCapsule: 1, // 是否显示左上角图标   1表示显示    0表示不显示
      title: '订单确认', // 导航栏 中间的标题
      textColor: '#FFFFFF', // 标题颜色
      bgColor: '#F75D0B', // 导航栏背景颜色
      isloading: false,
    },
    // 此页面 页面内容距最顶部的距离
    imgHttp: app.globalData.imgHttp,
    selected: true, //勾选协议
    assetId: '', //资产ID
    referrerId: '', //推荐人id
    cardData: {},
    buyerName: '',
    phone: '',
    isphone: true,
    referrerPhone: '',
    invitationText: '',
    countdown: 60,
    orderId: '',
    merchantId: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // var assetId = '1408248080599425025'
    // var referrerId = ''
    var assetId = options.assetId
    var referrerId = options.referrerId
    var merchantId = options.merchantId
    if (referrerId) {
      this.setData({
        isphone: false
      })
    }
    console.log('assetId', assetId)
    console.log('referrerId', referrerId)
    this.setData({
      assetId: assetId,
      referrerId: referrerId,
      merchantId: merchantId,
    })
    this.getDetail()
  },
  //获取订单详情
  getDetail() {
    var data = {
      assetId: this.data.assetId,
      referrerId: this.data.referrerId,
      merchantId: this.data.merchantId
    }
    WXAPI.confirmOrder(data, (res) => {
      console.log('订单确认页面', res)
      const {
        result
      } = res
      if (result.referrerPhone) {
        var invitationText = result.referrerName + '(' + result.referrerPhone + ')'
      } else {
        var invitationText = ''
      }
      console.log('订单确认页面', invitationText)
      this.setData({
        cardData: result,
        invitationText: invitationText
      })
    })
  },
  //卡详情
  handleDetail(e) {
    wx.navigateBack({
      delta: 1
    });
  },
  //股东购卡协议
  handleAgree(e) {
    var url = this.data.imgHttp + e.currentTarget.dataset.url
    var index = url.lastIndexOf("\.");
    var type = url.substring(index + 1, url.length);
    wx.downloadFile({
      url: url,
      header: {},
      success: function (res) {
        var filePath = res.tempFilePath;
        console.log(filePath);
        wx.openDocument({
          filePath: filePath,
          fileType: type,
          success: function (res) {
            console.log('打开文档成功')
          },
          fail: function (res) {
            console.log(res);
          },
          complete: function (res) {
            console.log(res);
          }
        })
      },
      fail: function (res) {
        console.log('文件下载失败');
      },
      complete: function (res) {},
    })

  },
  //勾选用户协议
  handleReading() {
    this.setData({
      selected: !this.data.selected
    })
    console.log('selected',this.data.selected)
  },
  //获取名字
  getname(e) {
    var buyerName = e.detail.value
    this.setData({
      buyerName: buyerName,
    })
  },
  getphone(e) {
    var phone = e.detail.value
    this.setData({
      phone: phone,
    })
  },
  handlepay() {
    var buyerName = this.data.buyerName
    var selected = this.data.selected
    
    // if (this.data.cardData.cardType == 1 || this.data.cardData.cardType == 4) {
    //   if (!buyerName) {
    //     wx.showToast({
    //       title: '请填写姓名',
    //       icon: 'none'
    //     })
    //     return
    //   }
    // }
    if (!selected) {
      console.log('selected', selected)
      wx.showToast({
        title: '请勾选协议',
        icon: 'none'
      })
      return
    }

    this.wxpay()
  },
  wxpay() {
    var that = this
    var data = {
      assetId: this.data.assetId,
      buyerName: this.data.buyerName,
      referrerId: this.data.referrerId,
      buyMoney: this.data.cardData.buyMoney,
      referrerPhone: this.data.phone,
      chainMerchantId: this.data.merchantId
    }
    console.log('data', data)
    WXAPI.createBuyOrder(data, (res) => {
      console.log('提交支付', res)
      if(res.code == 200){
        var data = res.result
        wx.requestPayment({
          'timeStamp': data.timeStamp,
          'nonceStr': data.nonceStr,
          'package': data.package,
          'signType': data.signType, //MD5
          'paySign': data.paySign,
          'success': function (res) {
            console.log('支付成功', res)
            console.log(res)
            if (res.errMsg == 'requestPayment:ok') {
              wx.showToast({
                title: '支付成功',
              })
              that.setData({
                orderId: data.orderId
              })
              that.getCardPayorder()
              // setTimeout(() => {
              //   //支付页面信息
              //   wx.redirectTo({
              //     url: '/userPageB/pages/userStore/resellScuuess/resellScuuess?orderId='+data.orderId+"&pathType=cardPay",
              //   })
              // }, 1500);
            }
          },
          'fail': function (res) {
            wx.showToast({
              title: '支付失败',
              icon: 'none'
            })
            console.log('支付失败或取消支付', res)
          },
          'complete': function (res) {
            console.log('支付完成', res)
            // wx.navigateBack({})
          }
        })
      }else{
        wx.showToast({
          title: res.message,
          icon: 'none'
        })
      }
     

    })
  },
  //购卡订单支付结果
  getCardPayorder() {
    const that = this
    this.setData({
      timer: setInterval(function () { //这里把setInterval赋值给变量名为timer的变量
        that.data.countdown--;
        var data = {
          orderId: that.data.orderId,
        }
        WXAPI.getBuyCardPayResult(data, (res) => {
          const data = res.result
          console.log("获取支付结果", res)
          if (data.isPay) {
            // wx.redirectTo({
            //   url: '/userPageB/pages/userStore/resellScuuess/resellScuuess?orderId=' + that.data.orderId + "&pathType=cardPay",
            // })
            wx.redirectTo({
              url: '/userPageB/pages/buyCardpuch/buyCardpuch?customerCardId=' + data.customerCardId,
            })
            clearInterval(that.data.timer);
          }
        })
        that.setData({
          countdown: that.data.countdown,
        })
        if (that.data.countdown == 0) {
          console.log("1111111111")
          clearInterval(that.data.timer);
          that.setData({
            countdown: 60,
          })
        }
      }, 1000)
    })

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  },
})